package com.wn.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wn.common.Const;
import com.wn.pojo.User;
import com.wn.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 让拦截器实现拦截自己想要求的功能
 */
@Component
public class JwInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置字符编码的格式
        response.setContentType("application/json;charset=utf-8");
        //获取cookie
        Cookie[] cookies = request.getCookies();
        String token=null;
        for(Cookie cookie :cookies){
            String cookieName = cookie.getName();
            if("token".equals(cookieName)){
              token = cookie.getValue();
            }
        }
        User user = JWTUtil.parserToken(token, Const.PUBLIC_KEY);
        //判断是否登录
        if(StringUtils.isEmpty(user)){
            Map<String,Object> map = new HashMap<>();
            map.put("status",1);
            map.put("msg","请先登录");
            //把map转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(map);
            //把json字符串以响应流的形式传递给前端
            PrintWriter writer = response.getWriter();
            writer.write(json);
            writer.flush();
            writer.close();
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
